// pages/task/task.js
const { formatTimeHM, getTimeDiff, generateId } = require('../../utils/util.js')

Page({
  data: {
    isEdit: false,
    task: {
      id: '',
      title: '',
      description: '',
      level: 1,
      priority: 2,
      completed: false,
      startTime: null,
      endTime: null,
      duration: null,
      parentId: null
    },
    subtasks: []
  },

  onLoad(options) {
    const { taskId, parentId, level } = options
    
    if (taskId) {
      // 编辑现有任务
      this.loadTask(taskId)
      this.setData({ isEdit: true })
    } else {
      // 创建新任务
      this.setData({
        'task.level': parseInt(level) || 1,
        'task.parentId': parentId || null
      })
    }
  },

  loadTask(taskId) {
    // 模拟加载任务数据
    const task = {
      id: taskId,
      title: '示例任务',
      description: '这是一个示例任务描述',
      level: 1,
      priority: 2,
      completed: false,
      startTime: '09:00',
      endTime: null,
      duration: null
    }
    
    // 模拟加载子任务
    const subtasks = [
      {
        id: generateId(),
        title: '子任务1',
        completed: true,
        duration: 30
      },
      {
        id: generateId(),
        title: '子任务2',
        completed: false,
        duration: null
      }
    ]

    this.setData({
      task,
      subtasks
    })
  },

  // 输入处理
  onTitleInput(e) {
    this.setData({
      'task.title': e.detail.value
    })
  },

  onDescInput(e) {
    this.setData({
      'task.description': e.detail.value
    })
  },

  setPriority(e) {
    const priority = parseInt(e.currentTarget.dataset.priority)
    this.setData({
      'task.priority': priority
    })
  },

  // 时间控制
  onStartTimer() {
    const task = this.data.task
    task.startTime = formatTimeHM(new Date())
    task.endTime = null
    task.duration = null
    this.setData({ task })
  },

  onStopTimer() {
    const task = this.data.task
    task.endTime = formatTimeHM(new Date())
    task.duration = getTimeDiff(
      new Date(`2024-01-01 ${task.startTime}`),
      new Date(`2024-01-01 ${task.endTime}`)
    )
    this.setData({ task })
  },

  onComplete() {
    const task = this.data.task
    task.completed = true
    if (task.startTime && !task.endTime) {
      this.onStopTimer()
    }
    this.setData({ task })
  },

  // 子任务操作
  onAddSubtask() {
    const currentLevel = this.data.task.level
    if (currentLevel >= 3) {
      wx.showToast({
        title: '已达到最大层级',
        icon: 'none'
      })
      return
    }

    wx.navigateTo({
      url: `/pages/task/task?parentId=${this.data.task.id}&level=${currentLevel + 1}`
    })
  },

  toggleSubtask(e) {
    const index = e.currentTarget.dataset.index
    const subtasks = this.data.subtasks
    subtasks[index].completed = !subtasks[index].completed
    this.setData({ subtasks })
  },

  onDeleteSubtask(e) {
    const index = e.currentTarget.dataset.index
    const subtasks = this.data.subtasks
    subtasks.splice(index, 1)
    this.setData({ subtasks })
  },

  // 保存任务
  onSave() {
    const { task } = this.data
    
    if (!task.title.trim()) {
      wx.showToast({
        title: '请输入任务标题',
        icon: 'none'
      })
      return
    }

    // 保存到云数据库
    this.saveTask(task)
    
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    })

    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  },

  saveTask(task) {
    // 实际应该调用云函数保存到数据库
    console.log('保存任务:', task)
  },

  // 删除任务
  onDelete() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个任务吗？',
      success: (res) => {
        if (res.confirm) {
          // 删除任务逻辑
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  },

  // 返回
  onBack() {
    wx.navigateBack()
  }
})